import { FieldObject, LabelValue, TableObject } from "@/type/global";
import { Col, Card, Form, Input, Select, Collapse, Row, Button, Checkbox, Empty, AutoComplete, Tooltip, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useEffect, useState } from "react";
import { getKeyName, saveTable } from "@/api";
import { fieldOptions, fieldTypeList, javaOptions, proTableOption, proTableSearchOption, proFormOption, proFormTypeOption } from "@/common";
import LazyImport from "../LazyImport";
import styles from './index.less'
import OptionImport from "../OptionImport";
import ExcelImport from "../ExcelImport";
import TableDrawer from "../TableDrawer";
const { Panel } = Collapse;

const TableConfig: React.FC<{ submit: (value: TableObject) => void }> = (props) => {


    const [mockData, setMockData] = useState<LabelValue[]>([]);


    const [table, setTable] = useState<TableObject>({
        tableName: 't_user',
        tableComment: '用户',
        fieldList: []
    });

    useEffect(() => {
        getKeyName().then(res => {
            setMockData(res.map(item => ({ label: item.desc || '', value: item.key })));
        })
    }, []);


    function handleFormChange(e: any, key: keyof FieldObject, index: number) {
        let value: any = e;
        if (value.target) {
            value = value.target.value;
        }
        const fieldList = table.fieldList!;
        const obj: FieldObject = fieldList![index];
        // 如果创建索引，那么加一个默认的索引名称
        if (key === 'options' && e.includes('index')) {
            obj['indexName'] = `index_${obj.fieldName}`;
        }
        (obj[key] as any) = value as string;
        fieldList[index] = obj;
        setTable({
            ...table,
            fieldList: fieldList
        })
    }

    function handleTableChange(e: any, key: string) {
        let tableObj: any = table;
        tableObj[key] = e.target.value;
        setTable({
            ...tableObj
        })
    }

    function handleDeleteField(e: React.MouseEvent, index: number) {
        e.stopPropagation();
        let fieldList = table.fieldList!;
        fieldList?.splice(index, 1);
        setTable({
            ...table,
            fieldList: fieldList
        })
    }

    function renderPanelHeader(item: FieldObject, index: number) {
        return <>
            <div>
                <Row>
                    <Col span={2}>
                        <span>字段名</span>
                    </Col>

                    <Col span={4}>
                        <Input onClick={(e) => e.stopPropagation()} value={item.fieldName} onChange={(e) => handleFormChange(e, 'fieldName', index)}></Input>
                    </Col>

                    {
                        item.options?.includes('index') &&
                        <>
                            <Col span={2} offset={1}>
                                <span>索引名</span>
                            </Col>

                            <Col span={4}>
                                <Input onClick={(e) => e.stopPropagation()} value={item.indexName} onChange={(e) => handleFormChange(e, 'indexName', index)}></Input>
                            </Col></>
                    }

                    <Col span={item.options?.includes('index') ? 11 : 18}>
                        <div style={{ textAlign: 'right' }}>
                            <Button onClick={(e) => handleDeleteField(e, index)} danger type='link'>
                                删除
                            </Button>
                        </div>
                    </Col>
                </Row>
            </div>
        </>
    }

    function handleAddField() {
        let fieldList = table.fieldList || [];
        fieldList.push({
            fieldName: 'demo',
            mockType: '',
            comment: '',
            fieldType: void 0,
            defaultValue: '',
            options: [],
            proFormOptions: [],
            proFormTypeOption: '',
            proTableOptions: [],
            proTableSearchOption: ''
        });
        setTable({
            ...table,
            fieldList: fieldList
        })
    }

    const filterOption = (inputValue: string, option: any) => option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1


    function handleConfirm(value: string) {
        const valueList: FieldObject[] = value.split(',').map(item => ({
            fieldName: item,
        }));
        setTable({
            tableName: 'test_table',
            tableComment: '测试表格',
            fieldList: valueList
        })
    }

    function handleOptionConfirm(value: string) {
        setTimeout(() => {
            setTable(JSON.parse(value));
        })
    }

    function handleExcelOk(result: FieldObject[]) {
        setTable({
            ...table,
            fieldList: result
        })
    }

    function handleSave() {
        if (!table.tableName) {
            message.warning('请输入表名称');
            return;
        }

        if (!table.fieldList || !table.fieldList.length) {
            message.warning('至少输入一个字段名');
            return;
        }

        if (!table.fieldList.every(item => item.fieldName)) {
            message.warning('请输入字段名');
            return;
        }
        saveTable(table).then(res => {
            message.success('保存成功');
        });
    }

    function handleImport(data: TableObject) {
        setTable({
            ...data
        })
    }

    return <Card title={`表格配置(${table.fieldList!.length})`}>
        <div className={styles['button-group']}>
            <LazyImport onConfirm={handleConfirm}></LazyImport>

            <OptionImport onConfirm={handleOptionConfirm}></OptionImport>

            <ExcelImport onOk={handleExcelOk}></ExcelImport>
        </div>
        <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ width: '10%' }}>表名：</span>
            <Input onChange={(e) => { handleTableChange(e, 'tableName') }} value={table.tableName} placeholder="请输入"></Input>
        </div>

        <div style={{ marginTop: '12px', marginBottom: '24px', display: 'flex', alignItems: 'center' }}>
            <span style={{ width: '10%' }}>
                描述:
            </span>
            <Input onChange={(e) => { handleTableChange(e, 'tableComment') }} value={table.tableComment} placeholder="请输入"></Input>
        </div>

        {
            (table.fieldList && table.fieldList.length) ? <Collapse>

                {
                    table.fieldList.map((item, index) => <Panel key={index} header={renderPanelHeader(item, index)}>

                        <Form>
                            <h3>数据库配置</h3>
                            <Row>
                                <Col span={7}>
                                    <Form.Item name="fieldType" label="类型" >
                                        <AutoComplete placeholder="请输入" filterOption={filterOption} options={fieldTypeList} value={item.fieldType} onChange={(e) => handleFormChange(e, 'fieldType', index)}>
                                        </AutoComplete>
                                        {/* <Select style={{ width: '100%' }} value={item.fieldType} onChange={(e) => handleFormChange(e, 'fieldType', index)} options={fieldTypeList} placeholder="请选择"></Select> */}
                                    </Form.Item>
                                </Col>
                                <Col span={1}>
                                </Col>
                                <Col span={7}>
                                    <Form.Item name="defaultValue" label="默认值" >
                                        <Input value={item.defaultValue} onChange={(e) => handleFormChange(e, 'defaultValue', index)} placeholder="请输入"></Input>
                                    </Form.Item>
                                </Col>
                                <Col span={1}>
                                </Col>
                                <Col span={7}>
                                    <Form.Item name="comment" label="描述" >
                                        <Input value={item.comment} onChange={(e) => handleFormChange(e, 'comment', index)} placeholder="请输入"></Input>
                                    </Form.Item>
                                </Col>
                            </Row>

                            <Row>
                                <Col span={7}>
                                    <Form.Item name="mockType" label="模拟数据">
                                        <Select onChange={(e) => handleFormChange(e, 'mockType', index)} options={mockData} value={item.mockType} placeholder="请选择"></Select>
                                    </Form.Item>
                                </Col>
                                <Col span={1}>
                                </Col>
                                <Col>
                                    <Form.Item name="options" label="配置">
                                        {item.options && <span></span>}
                                        <Checkbox.Group value={item.options} onChange={(e) => handleFormChange(e, 'options', index)}
                                            options={fieldOptions}
                                        />
                                    </Form.Item>
                                </Col>
                            </Row>
                            <h3 style={{ marginTop: '12px' }}>java 配置</h3>
                            <Row>
                                <Col>
                                    <Form.Item name="javaOptions">
                                        {item.javaOptions && <span></span>}
                                        <Checkbox.Group value={item.javaOptions} onChange={(e) => handleFormChange(e, 'javaOptions', index)}
                                            options={javaOptions}
                                        />
                                    </Form.Item>
                                </Col>
                            </Row>
                            <h3 style={{ marginTop: '12px' }}>表格配置</h3>
                            <Row>
                                <Col>
                                    <Form.Item name="proTableOptions" label="高级表格配置">
                                        {item.proTableOptions && <span></span>}
                                        <Checkbox.Group value={item.proTableOptions} onChange={(e) => handleFormChange(e, 'proTableOptions', index)}
                                            options={proTableOption}
                                        />
                                    </Form.Item>
                                </Col>

                                <Col span={24}>
                                    <Form.Item name="proTableSearchOption" label="高级表格搜索类型">
                                        {item.proTableSearchOption && <span></span>}
                                        <Select onChange={(e) => handleFormChange(e, 'proTableSearchOption', index)} placeholder="高级表格搜索类型" options={proTableSearchOption}></Select>
                                    </Form.Item>
                                </Col>
                            </Row>
                            <h3 style={{ marginTop: '12px' }}>表单配置</h3>
                            <Row>
                                <Col>
                                    <Form.Item name="proFormOptions" label="高级表格配置">
                                        {item.proFormOptions && <span></span>}
                                        <Checkbox.Group value={item.proFormOptions} onChange={(e) => handleFormChange(e, 'proFormOptions', index)}
                                            options={proFormOption}
                                        />
                                    </Form.Item>
                                </Col>

                                <Col span={24}>
                                    <Form.Item name="proFormTypeOption" label="高级表格搜索类型">
                                        {item.proFormTypeOption && <span></span>}
                                        <Select onChange={(e) => handleFormChange(e, 'proFormTypeOption', index)} placeholder="高级表格搜索类型" options={proFormTypeOption}></Select>
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                    </Panel>)
                }

            </Collapse> :
                <Empty />
        }

        <Button style={{ marginTop: '24px' }} onClick={handleAddField} type="dashed" icon={<PlusOutlined />} block>添加字段</Button>
        <TableDrawer onImport={handleImport}></TableDrawer>
        <Button style={{ marginTop: '24px', float: 'right' }} onClick={() => props.submit(table)} type='primary'>一键生成</Button>
        <Button style={{ marginTop: '24px', float: 'right', marginRight: '12px' }} onClick={handleSave} type='primary'>保存</Button>
    </Card>
}

export default TableConfig;
